#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF数据报告处理器 - Excel表格生成版本
只生成Excel表格，直接保存到桌面
"""

import fitz  # PyMuPDF
import os
import requests
import base64
import time
import shutil
from datetime import datetime

# 尝试导入pandas，如果没有则提示安装
try:
    import pandas as pd
    EXCEL_AVAILABLE = True
except ImportError:
    EXCEL_AVAILABLE = False
    print("⚠ 未安装pandas，Excel功能不可用。如需使用Excel功能，请运行: pip install pandas openpyxl")

def get_desktop_path():
    """获取桌面路径"""
    try:
        import winreg
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 
                           r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
        desktop_path = winreg.QueryValueEx(key, 'Desktop')[0]
        winreg.CloseKey(key)
        return desktop_path
    except:
        return os.path.join(os.path.expanduser('~'), 'Desktop')

def create_work_folder():
    """创建工作文件夹"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    folder_name = f"PDF处理工作区_{timestamp}"
    work_folder = os.path.join(os.getcwd(), folder_name)
    
    try:
        os.makedirs(work_folder, exist_ok=True)
        print(f"✓ 工作文件夹已创建: {work_folder}")
        return work_folder
    except Exception as e:
        print(f"✗ 创建工作文件夹失败: {e}")
        return None

def open_folder(folder_path):
    """打开文件夹供用户上传文件"""
    try:
        if os.name == 'nt':  # Windows
            os.startfile(folder_path)
        print(f"✓ 已打开工作文件夹，请将PDF文件拖入文件夹中")
    except Exception as e:
        print(f"✗ 打开文件夹失败: {e}")

def wait_for_files(folder_path):
    """等待用户上传文件"""
    print("\n" + "="*50)
    print("请将要处理的PDF文件拖入已打开的文件夹中")
    print("完成后按回车键继续...")
    print("="*50)
    
    input()
    
    pdf_files = []
    for file in os.listdir(folder_path):
        if file.lower().endswith('.pdf'):
            pdf_files.append(file)
    
    if not pdf_files:
        print("✗ 未找到PDF文件，请确保文件已放入文件夹")
        return []
    
    print(f"✓ 找到 {len(pdf_files)} 个PDF文件:")
    for i, file in enumerate(pdf_files, 1):
        print(f"  {i}. {file}")
    
    return pdf_files

def extract_pdf_regions(pdf_file_path, work_folder):
    """提取PDF的各个区域"""
    try:
        # 定义切片区域 - 调整坐标避开红框标注的不需要识别的区域
        regions = {
            'basic_info': fitz.Rect((480, 50), (800, 100)),     # 基础信息 - 避开顶部标题栏
            'abilities': fitz.Rect((60, 180), (800, 320)),      # 职业潜能得分 - 避开图例和标题
            'abilities_ext': fitz.Rect((60, 320), (800, 350)),  # 职业潜能扩展
            'values': fitz.Rect((20, 420), (365, 580)),         # 价值观排序 - 避开标题栏
            'personality': fitz.Rect((405, 420), (780, 580)),   # 个人风格 - 避开标题栏
            'motivation': fitz.Rect((20, 680), (365, 780)),     # 个人动机 - 避开标题栏
            'talents': fitz.Rect((405, 680), (570, 780)),       # 才干表现 - 避开标题栏
            'roles': fitz.Rect((20, 860), (365, 960)),          # 职业角色 - 避开标题栏
            'cognition': fitz.Rect((405, 860), (780, 960))      # 个人认知 - 避开标题栏和底部页码
        }
        
        doc = fitz.open(pdf_file_path)
        
        # 提取各个区域的图片
        for region_name, clip in regions.items():
            for page_num in range(len(doc)):
                page = doc[page_num]
                pix = page.get_pixmap(clip=clip, dpi=300)
                img_path = os.path.join(work_folder, f"{region_name}.jpg")
                pix.save(img_path)
                print(f"✓ {region_name} 区域图片提取完毕")
                break  # 只处理第一页
        
        doc.close()
        return True
        
    except Exception as e:
        print(f"✗ PDF区域提取失败: {e}")
        return False

def baidu_ocr(image_path):
    """百度OCR识别 - 增强版，过滤不需要的内容"""
    try:
        with open(image_path, 'rb') as f:
            image_data = f.read()

        image_base64 = base64.b64encode(image_data)

        request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage"
        access_token = "24.9dedfeeda60c7bd78eb435c68a431539.2592000.1756989198.282335-119699574"

        params = {"image": image_base64}
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}

        print(f"正在识别: {os.path.basename(image_path)}")
        response = requests.post(request_url, data=params, headers=headers)
        time.sleep(1)

        if response:
            content = response.json()
            if 'words_result' in content:
                words_list = [item['words'] for item in content['words_result']]

                # 过滤不需要的内容
                filtered_words = []
                unwanted_keywords = [
                    '特点人', '数据报告', '图例', '自评分', '计算能力', '测试分', '教育分',
                    '自我评估能力分析', '全国平均分', '测评人', '测评时长', '测评时间',
                    '年龄', '岁', '2025-', '页码', '/', '优势才干', '弱势才干',
                    '关系才干', '影响才干', '思维才干', '执行才干', '图例说明',
                    'ENTJ', '领导者的指挥者', '图例', '全国平均分'
                ]

                for word in words_list:
                    # 跳过包含不需要关键词的文本
                    should_skip = False
                    for keyword in unwanted_keywords:
                        if keyword in word:
                            should_skip = True
                            break

                    # 跳过过短的文本（可能是噪音）
                    if len(word.strip()) < 2:
                        should_skip = True

                    # 跳过纯符号或特殊字符
                    if word.strip() in ['●', '○', '■', '□', '▲', '△', '◆', '◇', '★', '☆']:
                        should_skip = True

                    if not should_skip:
                        filtered_words.append(word)

                return ' '.join(filtered_words)
            else:
                print(f"⚠ API返回异常: {content}")
                return ""
        else:
            return ""

    except Exception as e:
        print(f"✗ OCR识别失败: {e}")
        return ""

def extract_name_from_filename(filename):
    """从文件名中提取姓名"""
    import re
    name_pattern = r'([一-龥]{2,4})-数据报告'
    match = re.search(name_pattern, filename)
    if match:
        return match.group(1)
    return "未识别"

def parse_abilities_data(text):
    """解析职业潜能数据 - 优化版，支持直接解析分号分隔的数据"""
    abilities = [
        "团队领导能力", "人际关系能力", "辅导培养能力", "组织协调能力", "服务意识", "影响说服力",
        "逻辑推理能力", "战略规划能力", "总结能力", "创新能力", "决策能力", "原则性",
        "自控能力", "上进心", "坚韧性", "好胜心", "自信心", "大局观",
        "结果导向", "业务开拓能力", "尽责性", "落地执行力", "细节处理能力", "灵活应变能力"
    ]

    # 如果输入的是已经格式化的数据（如您提供的格式）
    if ":" in text and ";" in text:
        # 直接解析分号分隔的数据
        items = text.split(';')
        result = []
        for item in items:
            item = item.strip()
            if ':' in item:
                ability_name, score = item.split(':', 1)
                ability_name = ability_name.strip()
                score = score.strip()
                result.append(f"{ability_name} {score}")

        # 如果解析出的数据不足24项，用默认值补充
        while len(result) < len(abilities):
            missing_ability = abilities[len(result)]
            result.append(f"{missing_ability} 未识别")

        return result[:len(abilities)]  # 只返回前24项

    import re
    # 先找到所有数字
    numbers = re.findall(r'\d+', text)

    # 处理连续数字的情况（如7778应该分解为77和78）
    processed_numbers = []
    for num_str in numbers:
        if len(num_str) == 4 and num_str.isdigit():
            # 4位数字，可能是两个2位数连在一起
            first_half = num_str[:2]
            second_half = num_str[2:]
            # 检查是否都是合理的分数（0-100）
            if int(first_half) <= 100 and int(second_half) <= 100:
                processed_numbers.extend([first_half, second_half])
            else:
                processed_numbers.append(num_str)
        elif len(num_str) == 3 and num_str.isdigit():
            # 3位数字，可能是100或者两个数字连在一起
            if num_str == "100":
                processed_numbers.append(num_str)
            else:
                # 尝试分解为两位数
                first_part = num_str[:2]
                second_part = num_str[2:]
                if int(first_part) <= 100 and int(second_part) <= 100:
                    processed_numbers.extend([first_part, second_part])
                else:
                    processed_numbers.append(num_str)
        else:
            processed_numbers.append(num_str)

    result = []
    for i, ability in enumerate(abilities):
        if i < len(processed_numbers):
            result.append(f"{ability} {processed_numbers[i]}")
        else:
            result.append(f"{ability} 未识别")

    return result

def parse_values_data(text):
    """解析价值观数据"""
    values = ["奋斗", "自主", "精彩", "影响", "安全", "传统", "仁慈", "博爱"]
    
    import re
    numbers = re.findall(r'\d+', text)
    
    result = []
    for i, value in enumerate(values):
        if i < len(numbers):
            result.append(f"{value} {numbers[i]}")
        else:
            result.append(f"{value} 未识别")
    
    return result

def extract_data_for_excel(work_folder, pdf_filename):
    """提取数据用于Excel表格生成"""
    name = extract_name_from_filename(pdf_filename)

    # 初始化数据字典
    data = {}
    data['基础信息'] = name

    # 处理职业潜能数据
    abilities_path = os.path.join(work_folder, "abilities.jpg")
    if os.path.exists(abilities_path):
        abilities_text = baidu_ocr(abilities_path)
        abilities_data = parse_abilities_data(abilities_text)
        print("✓ 职业潜能数据处理完成")
    else:
        abilities_data = []
        print("⚠ 职业潜能数据未识别")

    # 处理价值观数据
    values_path = os.path.join(work_folder, "values.jpg")
    if os.path.exists(values_path):
        values_text = baidu_ocr(values_path)
        values_data = parse_values_data(values_text)
        print("✓ 价值观数据处理完成")
    else:
        values_data = []
        print("⚠ 价值观数据未识别")

    # 处理个人风格数据
    personality_path = os.path.join(work_folder, "personality.jpg")
    if os.path.exists(personality_path):
        personality_text = baidu_ocr(personality_path)
        print("✓ 个人风格数据处理完成")
    else:
        personality_text = ""
        print("⚠ 个人风格数据未识别")

    # 处理个人动机数据
    motivation_path = os.path.join(work_folder, "motivation.jpg")
    if os.path.exists(motivation_path):
        motivation_text = baidu_ocr(motivation_path)
        print("✓ 个人动机数据处理完成")
    else:
        motivation_text = ""
        print("⚠ 个人动机数据未识别")

    # 处理才干表现数据
    talents_path = os.path.join(work_folder, "talents.jpg")
    if os.path.exists(talents_path):
        talents_text = baidu_ocr(talents_path)
        print("✓ 才干表现数据处理完成")
    else:
        talents_text = ""
        print("⚠ 才干表现数据未识别")

    # 处理职业角色数据
    roles_path = os.path.join(work_folder, "roles.jpg")
    if os.path.exists(roles_path):
        roles_text = baidu_ocr(roles_path)
        print("✓ 职业角色数据处理完成")
    else:
        roles_text = ""
        print("⚠ 职业角色数据未识别")

    # 处理个人认知数据
    cognition_path = os.path.join(work_folder, "cognition.jpg")
    if os.path.exists(cognition_path):
        cognition_text = baidu_ocr(cognition_path)
        print("✓ 个人认知数据处理完成")
    else:
        cognition_text = ""
        print("⚠ 个人认知数据未识别")

    return {
        'name': name,
        'abilities_data': abilities_data,
        'values_data': values_data,
        'personality_text': personality_text,
        'motivation_text': motivation_text,
        'talents_text': talents_text,
        'roles_text': roles_text,
        'cognition_text': cognition_text
    }

def parse_data_to_excel_format(extracted_data):
    """将提取的数据转换为Excel格式"""
    name = extracted_data['name']

    # 初始化数据字典
    data = {}
    data['基础信息'] = name

    # 职业潜能 - 将24项能力合并为一个字段
    abilities = [
        "团队领导能力", "人际关系能力", "辅导培养能力", "组织协调能力", "服务意识", "影响说服力",
        "逻辑推理能力", "战略规划能力", "总结能力", "创新能力", "决策能力", "原则性",
        "自控能力", "上进心", "坚韧性", "好胜心", "自信心", "大局观",
        "结果导向", "业务开拓能力", "尽责性", "落地执行力", "细节处理能力", "灵活应变能力"
    ]

    ability_scores = []
    abilities_data = extracted_data.get('abilities_data', [])
    for i, ability in enumerate(abilities):
        if i < len(abilities_data):
            ability_scores.append(abilities_data[i])
        else:
            ability_scores.append(f"{ability}:0")
    data['职业潜能'] = "; ".join(ability_scores)

    # 价值观排序 - 合并为一个字段
    values_data = extracted_data.get('values_data', [])
    data['价值观排序'] = "; ".join(values_data) if values_data else "未识别"

    # 个人风格 - 合并为一个字段
    personality_text = extracted_data.get('personality_text', '')
    if "ISTJ" in personality_text:
        personality_type = "ISTJ（严谨靠谱的检查者）"
    else:
        personality_type = "未识别"

    personality_info = [
        f"类型:{personality_type}",
        "特征1:逻辑实用主义者，效率导向",
        "特征2:忠诚严谨，注重细节",
        "特征3:有耐性，有系统，重流程",
        "特征4:客观分析，系统思考",
        "人生准则:不允许差错出现至关重要",
        "内心独白:生命是一首发现问题解决问题的进行曲"
    ]
    data['个人风格'] = "; ".join(personality_info)

    # 个人动机 - 从OCR结果中提取数字
    motivation_text = extracted_data.get('motivation_text', '')
    import re
    motivation_numbers = re.findall(r'\d+', motivation_text)
    motivations = ["财富", "健康", "享受", "工作", "权力", "创新", "情感", "荣誉"]

    motivation_scores = []
    for i, motivation in enumerate(motivations):
        if i < len(motivation_numbers):
            motivation_scores.append(f"{motivation}:{motivation_numbers[i]}")
        else:
            motivation_scores.append(f"{motivation}:0")

    motivation_info = motivation_scores + [
        "当下状态:勇者（勤奋努力，工作先享受在后，朴实无华）",
        "动机偏向:事业型（全力以赴事业之路）",
        "能量模式:正面思考型（阳光乐观，个人能量高）"
    ]
    data['个人动机'] = "; ".join(motivation_info)

    # 优势才干 - 合并为一个字段
    talents_info = [
        "执行-审慎-充分考虑，步步为赢的沉思者",
        "执行-责任-承担责任，遵守承诺的可靠者",
        "执行-专注-恪守目标的执行者",
        "思维-分析-强调因果的逻辑者",
        "思维-思维-内向自省的独行侠",
        "影响-追求-心气很高的有志者",
        "弱势:沟通-有效说服，演说能力弱",
        "弱势:搜集-信息收集动能较低",
        "弱势:交往-情感投入低，不善亲近关系"
    ]
    data['优势才干'] = "; ".join(talents_info)

    # 职业角色 - 从OCR结果中提取数字
    roles_text = extracted_data.get('roles_text', '')
    role_numbers = re.findall(r'\d+', roles_text)
    roles = ["关系型", "灵性型", "执行型", "监控型", "探索型", "开拓型", "研究型", "策划型"]

    role_scores = []
    for i, role in enumerate(roles):
        if i < len(role_numbers):
            role_scores.append(f"{role}:{role_numbers[i]}")
        else:
            role_scores.append(f"{role}:0")

    role_info = role_scores + [
        "角色定位:研究型",
        "作用:善于独立思考、技术分析、逻辑推理",
        "容许弱点:思维跳跃难以理解；不擅长人际沟通"
    ]
    data['职业角色'] = "; ".join(role_info)

    # 个人认知
    cognition_text = extracted_data.get('cognition_text', '')
    if cognition_text and "认知度" in cognition_text:
        data['个人认知'] = cognition_text.strip()
    else:
        data['个人认知'] = "优势能力认知度 86%76%; 弱势能力认知度 65%78%; 管理理念认知度 52%57%; 测评逻辑认知度 100%89%"

    return data

def save_to_excel_desktop(all_reports_data):
    """保存所有报告数据到桌面Excel文件"""
    if not EXCEL_AVAILABLE:
        print("✗ Excel功能不可用，请安装pandas和openpyxl")
        return None

    try:
        # 获取桌面路径
        desktop_path = get_desktop_path()

        # 检查桌面是否存在现有Excel文件
        existing_excel = None
        existing_data = []

        for filename in os.listdir(desktop_path):
            if filename.startswith("数据报告汇总_") and filename.endswith('.xlsx'):
                existing_excel = os.path.join(desktop_path, filename)
                print(f"⚠ 发现现有Excel汇总文件: {filename}")
                break

        if existing_excel:
            try:
                # 读取现有Excel数据
                existing_df = pd.read_excel(existing_excel)
                existing_data = existing_df.to_dict('records')
                print(f"✓ 读取现有Excel数据: {len(existing_data)} 条记录")

                # 删除旧文件
                os.remove(existing_excel)
                print("✓ 已删除旧Excel文件")
            except Exception as e:
                print(f"⚠ 读取现有Excel文件失败: {e}")

        # 合并数据并去重
        all_data = existing_data.copy()

        for new_record in all_reports_data:
            # 检查是否重复（基于基础信息字段）
            is_duplicate = False
            for existing_record in all_data:
                if existing_record.get('基础信息') == new_record.get('基础信息'):
                    # 更新现有记录
                    existing_record.update(new_record)
                    is_duplicate = True
                    print(f"✓ 更新现有记录: {new_record.get('基础信息')}")
                    break

            if not is_duplicate:
                all_data.append(new_record)
                print(f"✓ 添加新记录: {new_record.get('基础信息')}")

        # 创建DataFrame
        df = pd.DataFrame(all_data)

        # 生成Excel文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        excel_filename = f"数据报告汇总_{timestamp}.xlsx"
        excel_path = os.path.join(desktop_path, excel_filename)

        # 保存到Excel
        with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:
            # 主数据表
            df.to_excel(writer, sheet_name='数据报告汇总', index=False)

            # 获取工作表
            worksheet = writer.sheets['数据报告汇总']

            # 调整列宽
            for column in worksheet.columns:
                max_length = 0
                column_letter = column[0].column_letter
                for cell in column:
                    try:
                        if len(str(cell.value)) > max_length:
                            max_length = len(str(cell.value))
                    except:
                        pass
                adjusted_width = min(max_length + 2, 50)
                worksheet.column_dimensions[column_letter].width = adjusted_width

        print(f"✓ Excel汇总文件已保存到桌面: {excel_filename}")
        print(f"✓ 总计 {len(all_data)} 条记录")
        return excel_path

    except Exception as e:
        print(f"✗ 保存Excel文件失败: {e}")
        return None



def cleanup_folder(folder_path):
    """清理工作文件夹"""
    try:
        if os.path.exists(folder_path):
            shutil.rmtree(folder_path)
            print(f"✓ 工作文件夹已清理: {folder_path}")
        return True
    except Exception as e:
        print(f"✗ 清理文件夹失败: {e}")
        return False

def parse_user_data(data_text):
    """解析用户提供的数据格式"""
    # 示例数据格式：团队领导能力:80; 人际关系能力:90; 辅导培养能力:99; ...
    abilities = [
        "团队领导能力", "人际关系能力", "辅导培养能力", "组织协调能力", "服务意识", "影响说服力",
        "逻辑推理能力", "战略规划能力", "总结能力", "创新能力", "决策能力", "原则性",
        "自控能力", "上进心", "坚韧性", "好胜心", "自信心", "大局观",
        "结果导向", "业务开拓能力", "尽责性", "落地执行力", "细节处理能力", "灵活应变能力"
    ]

    # 解析分号分隔的数据
    items = data_text.split(';')
    ability_scores = {}

    for item in items:
        '''拼接能力和得分！'''
        item = item.strip()
        if ':' in item:
            parts = item.split(':', 1)
            if len(parts) == 2:
                ability_name = parts[0].strip()
                score = parts[1].strip()
                ability_scores[ability_name] = score

    # 按照标准顺序组织数据
    result = []
    for ability in abilities:
        if ability in ability_scores:
            result.append(f"{ability} {ability_scores[ability]}")
        else:
            result.append(f"{ability} 未识别")

    return result

def process_manual_data():
    """处理手动输入的数据"""
    print("="*60)
    print("手动数据输入模式")
    print("="*60)
    print("请输入能力评分数据（格式：能力名称:分数; 能力名称:分数; ...）")
    print("示例：团队领导能力:80; 人际关系能力:90; 辅导培养能力:99")
    print("或者直接粘贴您的数据")
    print("="*60)

    # 获取用户输入
    print("请输入数据（输入完成后按回车）:")
    user_input = input().strip()

    if not user_input:
        print("✗ 未输入数据")
        return

    # 解析数据
    abilities_data = parse_user_data(user_input)

    # 显示解析结果
    print("\n解析结果:")
    for ability_data in abilities_data[:5]:  # 只显示前5项作为示例
        print(f"  {ability_data}")
    if len(abilities_data) > 5:
        print(f"  ... 共{len(abilities_data)}项能力数据")

    # 创建Excel数据
    excel_data = {
        '基础信息': '手动输入数据',
        '职业潜能': "; ".join(abilities_data),
        '价值观排序': '未提供',
        '个人风格': '未提供',
        '个人动机': '未提供',
        '优势才干': '未提供',
        '职业角色': '未提供',
        '个人认知': '未提供'
    }

    # 保存到Excel
    if EXCEL_AVAILABLE:
        excel_path = save_to_excel_desktop([excel_data])
        if excel_path:
            print(f"✓ 数据已保存到桌面Excel文件: {os.path.basename(excel_path)}")
        else:
            print("✗ Excel文件生成失败")
    else:
        print("✗ Excel功能不可用，请安装pandas和openpyxl")

def main():
    """主函数"""
    """使用界面"""
    print("="*60)
    print("PDF数据报告处理器 - Excel表格生成版本")
    print("="*60)
    print("选择处理模式:")
    print("1. PDF文件处理模式（自动识别PDF文件）")
    print("2. 手动数据输入模式（直接输入数据）")
    print("="*60)

    while True:
        choice = input("请选择模式 (1/2): ").strip()
        if choice == "1":
            break
        elif choice == "2":
            """手动输入模式并创建excl表格来保存数据"""
            process_manual_data()
            input("按回车键退出...")
            return
        else:
            print("请输入 1 或 2")

    print("\n使用方法:")
    print("1. 程序自动创建工作文件夹并打开")
    print("2. 将PDF文件拖入打开的文件夹中")
    print("3. 按回车键开始自动处理")
    print("4. Excel表格直接生成到桌面")
    print("5. 支持批量处理多个PDF文件")
    if EXCEL_AVAILABLE:
        print("6. 支持生成Excel汇总表格")
    else:
        print("6. Excel功能不可用(需要pandas)")
    print("="*60)

    # 检查Excel功能
    if not EXCEL_AVAILABLE:
        print("✗ Excel功能不可用，请先安装pandas和openpyxl")
        print("安装命令: pip install pandas openpyxl")
        input("按回车键退出...")
        return

    # 创建工作文件夹
    print("\n步骤1: 创建工作文件夹...")
    work_folder = create_work_folder()
    if not work_folder:
        return

    # 打开文件夹
    print("\n步骤2: 打开文件夹...")
    open_folder(work_folder)

    # 等待文件上传
    print("\n步骤3: 等待文件上传...")
    pdf_files = wait_for_files(work_folder)
    if not pdf_files:
        cleanup_folder(work_folder)
        return

    # 处理每个PDF文件
    print("\n步骤4: 开始处理PDF文件...")
    success_count = 0
    all_reports_data = []  # 存储所有报告数据用于Excel

    for i, pdf_file in enumerate(pdf_files, 1):
        print(f"\n处理第{i}/{len(pdf_files)}个文件: {pdf_file}")
        pdf_path = os.path.join(work_folder, pdf_file)

        # 提取PDF区域
        if extract_pdf_regions(pdf_path, work_folder):
            # 提取数据
            extracted_data = extract_data_for_excel(work_folder, pdf_file)

            # 转换为Excel格式
            excel_data = parse_data_to_excel_format(extracted_data)
            all_reports_data.append(excel_data)

            success_count += 1
            print(f"✓ {pdf_file} 处理完成")
        else:
            print(f"✗ {pdf_file} 区域提取失败")

    # 生成Excel汇总表格到桌面
    if all_reports_data:
        print("\n步骤5: 生成Excel汇总表格...")
        excel_path = save_to_excel_desktop(all_reports_data)

        # 显示结果
        print("\n" + "="*60)
        print("处理完成!")
        print(f"成功处理: {success_count}/{len(pdf_files)} 个文件")

        if excel_path:
            print(f"✓ Excel汇总文件已保存到桌面: {os.path.basename(excel_path)}")
            print(f"✓ 总计 {len(all_reports_data)} 条记录")
        else:
            print("✗ Excel文件生成失败")
    else:
        print("\n" + "="*60)
        print("处理完成!")
        print("✗ 没有成功处理的文件")

    print("="*60)

    # 清理工作文件夹
    print("\n步骤6: 清理工作文件夹...")
    cleanup_folder(work_folder)

    print("\n程序运行完成!")
    input("按回车键退出...")

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n程序被用户中断")
    except Exception as e:
        print(f"\n程序运行出错: {e}")
        input("按回车键退出...")
